/*
 * @(#)JsonUtil.java
 *
 * Copyright 2012 by ShenY BIS, All rights reserved.
 */
package com.bis.framework.util.business.chinamobile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;

/**
 * JsonUtil
 * 
 * JSON和BEAN之间的转换工具类。
 * 
 * @author BIS 2012-12-24
 */
public class JsonUtil
{

    public static JsonGenerator         jsonGenerator = null;
    public static ObjectMapper          objectMapper  = null;
    public static ByteArrayOutputStream baos          = null;

    //	#start	【构造方法】
    /**
     * 构造方法
     */
    static
    {
        try
        {
            //  初始化
            if (objectMapper == null)
            {
                objectMapper = new ObjectMapper();
            }

            if (objectMapper != null && jsonGenerator == null)
            {
                baos = new ByteArrayOutputStream();
                jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(baos, JsonEncoding.UTF8);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    //	#end

    //	#start	【BEAN-->JSON】
    /**
     * ENTITY TO JSON
     * @throws IOException 
     * @throws JsonProcessingException 
     */
    public synchronized static String writeEntityJSON(Object bean) throws JsonProcessingException, IOException
    {
        jsonGenerator.writeObject(bean);
        baos.reset();
        objectMapper.writeValue(baos, bean);
        String strR = baos.toString("utf-8");
        return strR;
    }

    //	#end

    //	#start	【JSON-->BEAN】
    /**
     * JSON-->BEAN
     */
    public synchronized static Object readJson2Entity(String json, Object objP)
    {
        try
        {
            Object objR = objectMapper.readValue(json, objP.getClass());
            return objR;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }
    //	#end
}
